package thread.wang_bao_ling.c36;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class InsertAllTest {
    private long id = 0;
    private static ExecutorService ex = Executors.newFixedThreadPool(5);
    private static BlockingQueue<User> bq = new LinkedBlockingQueue(2000);

    public static void main(String[] args) {
        InsertAllTest test = new InsertAllTest();
        test.startProduct();
        test.startConsume();
    }


    /**
     * 启动生产者线程
     */
    public void startProduct() {
        new Thread(() -> {
            while (true) {
                try {
                    //每0.1s生产一个用户
                    bq.add(new User(++id));
                    System.out.println(bq.size());
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "produce").start();
    }

    /**
     * 启动消费线程
     */
    public void startConsume() {
        for (int i = 0; i < 5; i++) {
            ex.execute(() -> {
                try {
                    while (true) {
                        execTasks(getTasks());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     * 获取批量任务
     * @return
     * @throws InterruptedException
     */
    public List<User> getTasks() throws InterruptedException {
        List<User> linkList = new LinkedList<>();
        User user;
        user = bq.take();
        linkList.add(user);
        while ((user = bq.poll()) != null) {
            linkList.add(user);
        }
        return linkList;
    }


    /**
     * 执行批量插入
     *
     * @param list
     * @throws InterruptedException
     */
    public void execTasks(List<User> list) throws InterruptedException {
        StringBuffer sb=new StringBuffer();
        list.stream().forEach(c->{
            sb.append(c);
        });
        System.out.println(Thread.currentThread().getName()+"执行批量插入，插入内容为："+sb);
        Thread.sleep(3000);
    }

}
